package com.ruicar.afs.cloud.common.mq.rabbit.register;

import cn.hutool.core.util.ReflectUtil;
import com.ruicar.afs.cloud.common.core.spring.DynamicBeanHelper;
import com.ruicar.afs.cloud.common.core.util.AfsResourcesScanner;
import com.ruicar.afs.cloud.common.mq.rabbit.anno.send.AfsRabbitMqClient;
import com.ruicar.afs.cloud.common.mq.rabbit.anno.send.AfsRabbitMqSender;
import com.ruicar.afs.cloud.common.mq.rabbit.proxy.AfsMqClientInterfaceProxy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.type.AnnotationMetadata;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class AfsRabbitMqSenderRegister implements ImportBeanDefinitionRegistrar {
    public static Map<String, Class> fallBackDefineMap = new HashMap<>();

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AfsResourcesScanner
                .scanClassByAnnotation(new String[]{"com.ruicar.afs.cloud"}, AfsRabbitMqClient.class)
                .forEach(clazz -> {
                    DynamicBeanHelper.registerInterface(clazz, AfsMqClientInterfaceProxy.class, registry);
                    Method[] methods = ReflectUtil.getMethods(clazz);
                    for (Method method : methods) {
                        AfsRabbitMqSender rabbitSender = AnnotationUtils.findAnnotation(method, AfsRabbitMqSender.class);
                        if (rabbitSender != null) {
                            fallBackDefineMap.put(rabbitSender.queueName(), rabbitSender.fallBack());
                        }
                    }
                });


    }
}
